<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\admin\model\ProductKind;
use app\admin\model\ProductLogic;
class Product extends Common
{
	function product_list(){
		$ProductCat = new ProductKind();
		$cats = $ProductCat->product_kind_list(0,0);
    	$this->assign('cat_select',$cats);
		return view();
	}

	function ajax_product_list(){
		$get_data = input("get.");
		$data = input("post.");

		$list = array();
        $p = empty($_GET['p']) ? 1 : $_GET['p'];
        $size = empty($_REQUEST['size']) ? 25 : $_REQUEST['size'];
        $where = "1=1";
        if ($data['kind_id']){
            $where .= " and kind_id=".$data['kind_id'];
        }
        if ($data['keyword']){
        	$where .= " and title like '%".$data['keyword']."%'";
        }
        $count = db('product')->where($where)->count();// 查询满足要求的总记录数

        $list = db('product')->where($where)->order('sort_order,id desc')->paginate($size,$count)->each(function($item,$key){
        	return $item;
        });
        $page = $list->render();

        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('count',$count);

        return view();
	}

	function product_form(){
		$ProductLogic = new ProductLogic();
		if(request()->isAjax()){
			$post_data = input('post.');
			$id = $post_data['id'];
			//保存属性到产品表
			// foreach($post_data as $k=>$v){
			// 	if(strstr($k, 'attr_')){
			// 		$attr_list[] = $v;
			// 	}
			// }
			// if($attr_list){
			// 	foreach($attr_list as $k=>$v){
			// 		$attr[] = $v[0];
			// 	}
			// }
			// if(!empty($attr)){
			// 	$attr_str = '|';
			// 	$attr_str .= implode('|',$attr);
			// 	$attr_str .= '|';
			// 	$data['attr_list'] = $attr_str;
			// }

			$data['link_url'] = $post_data['link_url'];
			$data['is_en'] = $post_data['is_en'];
			$data['title'] = $post_data['title'];
			$data['e_title'] = $post_data['e_title'];
			$data['sub_title'] = $post_data['sub_title'];
			$data['market_price'] = $post_data['market_price'];
			$data['shop_price'] = $post_data['shop_price'];
			$data['kind_id'] = $post_data['kind_id'];
			$data['thumb'] = $post_data['thumb'];
			$data['image'] = $post_data['image'];
			$data['introduce'] = $post_data['introduce'];
			$data['content'] = $post_data['content'];
			$data['phone_content'] = $post_data['phone_content'];
			$data['con1'] = $post_data['con1'];
			$data['con2'] = $post_data['con2'];
			$data['con3'] = $post_data['con3'];
			$data['con4'] = $post_data['con4'];
			$data['con5'] = $post_data['con5'];
			$data['sort_order'] = $post_data['sort_order']==''?998:$post_data['sort_order'];
			$data['is_hide'] = $post_data['is_hide']==''?0:$post_data['is_hide'];
			$data['is_tj'] = $post_data['is_tj'];
			$data['is_hot'] = $post_data['is_hot'];
			$data['is_best'] = $post_data['is_best'];
			$data['keywords'] = $post_data['keywords']?$post_data['keywords']:$post_data['title'];
			$data['description'] = $post_data['description']?$post_data['description']:$post_data['title'];
			$data['web_title'] = $post_data['web_title']?$post_data['web_title']:$post_data['title'];

			if(!empty($post_data['slide_img'])){
	            $s_img = $post_data['slide_img'];
	            $s_alt = $post_data['slide_alt'];
	            $s_order = $post_data['slide_order'];
	            for($i=0;$i<count($s_img);$i++){
	                $s_order[$i] = empty($s_order[$i])?50:$s_order[$i];
	                $pics[] = array(
	                    'image'=>$s_img[$i],
	                    'alt'=>$s_alt[$i],
	                    'order'=>$s_order[$i],
	                );
	            }
	            // dump($pics);
	            //排序开始，数组中根据某个元素排序
	            $sort = array(
	             'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
	             'field'     => 'order',    //排序字段
	            );
	            $arrSort = array();
	            foreach($pics AS $uniqid => $row){
	                foreach($row AS $key=>$value){
	                    $arrSort[$key][$uniqid] = $value;
	                }
	            }
	            if($sort['direction']){
	                array_multisort($arrSort[$sort['field']], constant($sort['direction']), $pics);
	            }
	            //排序结束
	            // dump($pics);exit;
	            $data['pics'] = json_encode($pics);
	        }else{
	            $data['pics'] = '';
	        }

			if($id>0){
				$res = db('product')->where('id='.$id)->update($data);
				// $res2=$ProductLogic->saveGoodsAttr($id, $data['kind_id'],input('post.')); // 处理商品 属性
				if($res !== false){
					$json = array('status'=>1,'message'=>'编辑产品成功');
					/*********************记录日志***********************/
            		addLog(session('user_name').'编辑产品成功-'.$data['title'].' [ ID:'.$id.' ]');
				}else{
					$json = array('status'=>0,'message'=>'编辑产品失败');
				}
				echo json_encode($json);exit;
			}else{
				$res = db('product')->insertGetId($data);
				if($res){
					// $ProductLogic->saveGoodsAttr($res, $data['kind_id'],input('post.')); // 处理商品 属性
					$json = array('status'=>1,'message'=>'添加产品成功');
					/*********************记录日志***********************/
            		addLog(session('user_name').'添加产品成功-'.$data['title'].' [ ID:'.$res.' ]');
				}else{
					$json = array('status'=>0,'message'=>'添加产品失败');
				}
				echo json_encode($json);exit;
			}
		}else{
			$id = input('route.id');
			if($id>0){
				$one = db('product')->where('id='.$id)->find();
				$one['pics_arr'] = json_decode($one['pics']);
				$this->assign('one',$one);
			}
			$ProductCat = new ProductKind();
			$cats = $ProductCat->product_kind_list(0,$one['kind_id']);
        	$this->assign('cat_select',$cats);
			return view();
		}
	}

	function product_del(){
		$id = input('post.id');
		$data = db('product')->where('id='.$id)->find();
		$res = db('product')->where('id='.$id)->delete();
		if($res){
			$json = array('status'=>1,'message'=>'删除产品成功');
			/*********************记录日志***********************/
            addLog(session('user_name').'删除产品成功-'.$data['title'].' [ ID:'.$data['id'].' ]');
		}else{
			$json = array('status'=>0,'message'=>'删除产品失败');
		}
		echo json_encode($json);exit;
	}

	function kind_list(){
		$list = array();
        $p = empty($_GET['p']) ? 1 : $_GET['p'];
        $size = empty($_REQUEST['size']) ? 100 : $_REQUEST['size'];

        $count = db('product_kind')->where($where)->count();// 查询满足要求的总记录数

        $list = db('product_kind')->where($where)->order('sort_order,kind_id')->paginate($size,$count)->each(function($item,$key){
        	return $item;
        });
        $page = $list->render();

        $this->assign('total',$count);
        $this->assign('page',$page);
        $this->assign('list',$list);

        $ProductCat = new ProductKind(); 
        $cat_list = $ProductCat->product_kind_list(0, 0, false);
        $this->assign('cat_list',$cat_list);
        
        return view();
	}

	function kind_form(){
		if(request()->isAjax()){
			$ProductCat = new ProductKind();
			$data = input('post.');
			$data['sort_order'] = $data['sort_order']?$data['sort_order']:50;
			$data['keywords'] = $data['keywords']?$data['keywords']:$data['kind_name'];
			$data['description'] = $data['description']?$data['description']:$data['kind_name'];
			$data['web_title'] = $data['web_title']?$data['web_title']:$data['kind_name'].'_'.$this->config['site_name'];
			// dump($data);exit;
			$kind_id = $data['kind_id'];
			$act = $data['act'];
			if($act=='edit' && $kind_id>0){
				if ($data['kind_id'] == $data['parent_id']) 
				{
	        		//$this->error("所选分类的上级分类不能是当前分类",U('Admin/Article/category',array('id'=>$data['id'])));
	                $json['status'] = 0;
	                $json['message'] = "所选分类的上级分类不能是当前分类！";
	                echo json_encode($json);
	                return;
	        	}
	        	$children = array_keys($ProductCat->product_kind_list($data['kind_id'], 0, false)); // 获得当前分类的所有下级分类
	        	if (in_array($data['parent_id'], $children))
	        	{
	        		//$this->error("所选分类的上级分类不能是当前分类的子分类",U('Admin/Article/category',array('id'=>$data['id'])));
	                $json['status'] = 0;
	                $json['message'] = "所选分类的上级分类不能是当前分类的子分类！";
	                echo json_encode($json);
	                return;
	        	}
				unset($data['kind_id']);
				unset($data['act']);
				$res = db('product_kind')->where("kind_id=".$kind_id)->update($data);
				if($res !== false){
					$ProductCat->refresh_cat($kind_id);//修改分类族谱，级别
					$json = array('status'=>1,'message'=>'编辑成功');
					/*********************记录日志***********************/
            		addLog(session('user_name').'编辑产品分类成功-'.$data['kind_name'].' [ ID:'.$kind_id.' ]');
					echo json_encode($json);exit;
				}else{
					$json = array('status'=>0,'message'=>'编辑失败');
					echo json_encode($json);exit;
				}
			}elseif($act == 'add'){
				unset($data['kind_id']);
				unset($data['act']);
				$res = db('product_kind')->insertGetId($data);
				if($res){
					$ProductCat->refresh_cat($res);//修改分类族谱，级别
					$json = array('status'=>1,'message'=>'添加成功');
					/*********************记录日志***********************/
            		addLog(session('user_name').'添加产品分类成功-'.$data['kind_name'].' [ ID:'.$res.' ]');
					echo json_encode($json);exit;
				}else{
					$json = array('status'=>0,'message'=>'添加失败');
					echo json_encode($json);exit;
				}
			}else{
				$json = array('status'=>0,'message'=>'参数错误');
				echo json_encode($json);exit;
			}
		}else{
			$kind_id = input('route.kind_id');
			
			if($kind_id>0){
				$act = 'edit';
				$one = db('product_kind')->find($kind_id);
				$this->assign('one',$one);
				
			}else{
				$act = 'add';
			}
			$this->assign('act',$act);

			$ProductCat = new ProductKind(); 
	        $pid = empty($one['parent_id'])?'':$one['parent_id'];
	        $cats = $ProductCat->product_kind_list(0,$pid,true);
	        $this->assign('cat_select',$cats);

			return view();
		}
	}

	function kind_del(){
		$kind_id = input('post.kind_id');
		$data = db('product')->where("kind_id=".$kind_id)->count();
		if($data>0){
        	$json = array('status'=>0,'message'=>'该分类存在产品信息，不能删除');
        	echo json_encode($json);exit;
        }
        $data = db('product_kind')->find($kind_id);
        $res = db('product_kind')->delete($kind_id);
        if($res){
            $json = array('status'=>1,'message'=>'删除成功！');
            /*********************记录日志***********************/
            addLog(session('user_name').'删除产品分类成功-'.$data['kind_name'].' [ ID:'.$data['kind_id'].' ]');
        }else{
            $json = array('status'=>0,'message'=>'删除失败');
        }
        echo json_encode($json);exit;
	}

	/**
     * 商品类型  用于设置商品的属性
     */
    public function productTypeList(){

        $list = array();
        $p = empty($_GET['p']) ? 1 : $_GET['p'];
        $size = empty($_REQUEST['size']) ? 20 : $_REQUEST['size'];

        $count = db('product_type')->count();// 查询满足要求的总记录数

        $list = db('product_type')->order('id desc')->paginate($size,$count)->each(function($item,$key){
        	return $item;
        });
        $page = $list->render();

        $this->assign('total',$count);
        $this->assign('show',$page);
        $this->assign('goodsTypeList',$list);
        // dump($goodsTypeList);exit;
        return view();
    }

    /**
     * 添加修改编辑  商品属性类型
     */
    public  function addEditProductType(){
        if(request()->isPost()) {
        	$data = input('post.');
        	$id = $data['id'];
            if($id>0)
            	db('productType')->where("id=".$id)->update($data);
            else
                db('productType')->insertGetId($data);

            $this->success("操作成功!!!",url('Admin/Product/productTypeList'));
            exit;
        }
        $goodsType = db('productType')->find(input('get.id'));
        $this->assign('goodsType',$goodsType);
        
        return view();
    }

    /**
     * 删除商品类型
     */
    public function delProductType(){
        // 判断 商品属性
        $id = input('route.id');
        $count = db("ProductAttribute")->where("type_id = ".$id)->count("1");
        $count > 0 && $return_arr = array('status' => -1, 'msg'   => '该类型下有商品属性不得删除',  'data' => url('Admin/Product/productTypeList'));
        // 删除分类
        if(empty($return_arr)){
            $return = db('ProductType')->where("id = ".$id)->delete();
            if($return)
                $return_arr = array('status' => 1, 'msg'   => '操作成功',  'data' => url('Admin/Product/productTypeList'));
            else
                $return_arr = array('status' => -1, 'msg'   => '操作失败', 'data' => url('Admin/Product/productTypeList'));
        }
        echo json_encode($return_arr);exit;
    }

    /**
     * 商品属性列表
     */
    public function productAttributeList(){
        $ProductCat = new ProductKind();
		$cats = $ProductCat->product_kind_list(0,0);
    	$this->assign('cat_select',$cats);
        
        return view('productAttributeList');
    }

    public function ajaxProductAttributeList(){
    	$where = '1=1'; // 搜索条件
        input('post.kind_id')   && $where = "$where and kind_id = ".input('post.kind_id') ;

    	$get_data = input("get.");
		$data = input("post.");

		$list = array();
        $p = empty(input('get.p')) ? 1 : input('get.p');
        $size = empty(input('post.size')) ? 25 : input('post.size');

        $count = db('productAttribute')->where($where)->count();// 查询满足要求的总记录数

        $list = db('productAttribute')->where($where)->order('`order` desc,attr_id DESC')->paginate($size,$count)->each(function($item,$key){
        	return $item;
        });
        $page = $list->render();
        // dump($list);exit;
        $this->assign('productAttributeList',$list);
        $this->assign('page',$page);
        $this->assign('count',$count);

        $productTypeList = db("productType")->column('id,name');
        $attr_input_type = array(0=>'手工录入',1=>' 从列表中选择',2=>' 多行文本框');
        $this->assign('attr_input_type',$attr_input_type);
        $this->assign('productTypeList',$productTypeList);

        $productKindList = db("productKind")->column('kind_id,kind_name');
        $this->assign('productKindList',$productKindList);

        return view('ajaxProductAttributeList');
    }

    /**
     * 添加修改编辑  商品属性
     */
    public  function addEditProductAttribute(){
    	$postData = input('post.');
    	$getData = input('get.');
    	$routeData = input('route.');
        $type = $postData['attr_id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        // dump($routeData);exit;
        $postData['attr_values'] = str_replace('_', '', $postData['attr_values']); // 替换特殊字符
        $postData['attr_values'] = str_replace('@', '', $postData['attr_values']); // 替换特殊字符
        $postData['attr_values'] = trim($postData['attr_values']);

        if((input('route.is_ajax') == 1) && request()->isAjax())//ajax提交验证
        {
        	// dump(input('post.'));exit;
                // C('TOKEN_ON',true); //  form表单提交
                if ($type == 2)
                {
                    // $model->save(); // 写入数据到数据库
                    db('productAttribute')->where("attr_id=".$postData['attr_id'])->update($postData);
                }
                else
                {
                    $insert_id = db('productAttribute')->insertGetId($postData); // 写入数据到数据库
                }
                $return_arr = array(
                    'status' => 1,
                    'msg'   => '操作成功',
                    'data'  => array('url'=>url('Admin/product/productAttributeList')),
                );
                echo json_encode($return_arr,true);exit;
        }
        // 点击过来编辑时
        $routeData['attr_id'] = $routeData['attr_id'] ? $routeData['attr_id'] : 0;
        // dump($routeData);exit;
        $productTypeList = db("productType")->select();
        $productAttribute = db('productAttribute')->find($routeData['attr_id']);
        $this->assign('productTypeList',$productTypeList);
        $this->assign('productAttribute',$productAttribute);

        // $productKindList = db("productKind")->select();
        // $this->assign('productKindList',$productKindList);
        $ProductCat = new ProductKind();
		$cats = $ProductCat->product_kind_list(0,$productAttribute['kind_id']);
    	$this->assign('cat_select',$cats);
        
        return view('productAttribute');
    }

    /**
     * 删除商品属性
     */
    public function delProductAttribute()
    {
        // 判断 有无商品使用该属性
        $count = db("ProductAttr")->where("attr_id = ".input('route.id'))->count("1");
        $count > 0 && $this->error('有商品使用该属性,不得删除!',url('Admin/Product/productAttributeList'));
        // 删除 属性
        db('ProductAttribute')->where("attr_id = ".input('route.id'))->delete();
        $this->success("操作成功!!!",url('Admin/Product/productAttributeList'));
    }



    /**
     * 动态获取商品属性输入框 根据不同的数据返回不同的输入框类型
     */
    public function ajaxGetAttrInput(){
    	$kind_id = input('get.kind_id');
    	$kind = db("ProductKind")->where("kind_id=".$kind_id)->find();
        $ProductLogic = new ProductLogic();
        $str = $ProductLogic->getAttrInput(input('get.product_id'),$kind['kind_id']);
        exit($str);
    }

    /*
    **复制文章
    */
    function productcopy(){
        $id = input('post.article_id');
        $data = db("Product")->where(array('id'=>$id))->find();
        unset($data['id']);
        $re = db("Product")->insertGetId($data);
        if ($re!==false){
            $json['status'] = 1;
            $json['message'] = '复制产品成功';
            /*********************记录日志***********************/
            // addLog(session('user_name').'复制产品成功-'.$data['title'].' [ ID:'.$data['article_id'].' ]');
        } else {
            $json['status'] = 0;
            $json['message'] = '复制产品失败';
        }
        echo json_encode($json);return;
    }











}